package com.jingtai.shop.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jingtai.common.constants.RedisConstant;
import com.jingtai.common.utils.ResponseUtil;
import com.jingtai.common.webfacade.error.ErrorEnum;
import com.jingtai.common.webfacade.response.ResponseMsg;
import com.jingtai.shop.common.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * Description: JWT过滤器
 * Create DateTime: 2020-03-23 17:54
 *
 * @author houyi
 */
@Slf4j
public class JwtAuthorizationTokenInterceptor implements HandlerInterceptor {

    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.expiration}")
    private Integer expiration;

    @Value("${jwt.tokenStart}")
    private String tokenStart;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestHeader = request.getHeader(tokenHeader);
        Long userId = null;
        String authToken = null;
        String headerStart = tokenStart + " ";
        if (requestHeader != null && requestHeader.startsWith(headerStart)) {
            authToken = requestHeader.substring(headerStart.length());
            try {
                userId = jwtTokenUtils.getUserIdFromToken(authToken);
            } catch (Exception e) {
                ResponseUtil.sendError(JSON.toJSONString(ResponseMsg.failed(ErrorEnum.TOKEN_INVALID)),response);
                return false;
            }
        }else{
            ResponseUtil.sendError(JSON.toJSONString(ResponseMsg.failed(ErrorEnum.TOKEN_INVALID)),response);
            return false;
        }

        if (ObjectUtil.isNotEmpty(userId)) {
            String tokenFromRedis = redisTemplate.opsForValue().get(RedisConstant.LOGIN_USER_PRE_KEY + userId);
            if (StringUtils.isNotBlank(tokenFromRedis)) {
                JSONObject jsonObject = JSONObject.parseObject(tokenFromRedis);
                String username = jwtTokenUtils.getUsernameFromToken(authToken);
                String token = jwtTokenUtils.getTokenFromRedis(jsonObject);
                //如果长时间未操作result为null
                if (StringUtils.isNotBlank(token)) {

                    //保证用户单终端登录
                    if (StringUtils.equals(authToken, token)) {
                        //校验token的有效性
                        if (jwtTokenUtils.validateToken(authToken, username)) {
                            redisTemplate.opsForValue().set(RedisConstant.LOGIN_USER_PRE_KEY + userId, tokenFromRedis, expiration, TimeUnit.HOURS);
                            return true;
                        }
                    }
                }
            }
        }
        ResponseUtil.response401(response);
        return false;
    }
}
